

package de.au.fi.imp.reader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

import org.openqa.selenium.By;

import de.au.fi.domain.StockIdMapping;

public class YahooFinanceIsinReader extends WebReader {

	public YahooFinanceIsinReader() {
		getFirefoxDriver();
	}
	
	public List<StockIdMapping> getIdMappingsForTickers(List<String> tickers) {
		
		if (tickers == null)
		{
			log.error("input tickers null, returning");
			return null;
		}
		List<StockIdMapping> idMappings = new ArrayList<StockIdMapping>();
		for (String ticker : tickers) {
			driver.get("http://de.finance.yahoo.com/q?s="+ticker+"&ql=0");
			try {
				StockIdMapping idMapping = getStockIdMapping(ticker);
				idMappings.add(idMapping);
			} catch (Exception e) {
				log.error("Could not get isin for ticker {}", ticker);
			}
		}
		if(tickers.size() != idMappings.size())
		{
			Object[] params = {new Integer(tickers.size()), new Integer(idMappings.size()), new Integer(tickers.size()-idMappings.size())};
			log.error("size tickers={} size isins {}, so {} isins could not be found", params);
		}
		return idMappings;
	}

	public List<StockIdMapping> getIdMappingsForTickers(String... tickers) {
		if (tickers == null)
			return null;
		return getIdMappingsForTickers(Arrays.asList(tickers));

	}

	private StockIdMapping getStockIdMapping(String ticker) throws Exception
	{
		StockIdMapping stockIdMapping = new StockIdMapping();
		setElementTo(By
				.xpath("/html/body/div/div[2]/div[3]/div[2]/div/div/div/span"));
		String info = getText();
		info = info.replace("Ticker:", "").replace("ISIN:", "").replace("/", "").replace("(", "").replace(")", "");
		StringTokenizer st = new StringTokenizer(info, " ");
		List<String> values = new ArrayList<String>();
		while (st.hasMoreElements()) {
			String string = (String) st.nextElement();
			values.add(string);
		}
		stockIdMapping.setTickerYahooData(ticker);
		stockIdMapping.setTickerYahooFinance(values.get(2));
		stockIdMapping.setIsin(values.get(3));
		return stockIdMapping;
	}

}
